import { OneModal } from '@/components/one-ui';
import React, { Ref, useRef, useEffect, useState, useMemo, useCallback } from 'react';
import { IOneModalRef } from '@/pages/type';
import { Button, Col, Form, Input, Row, Select, Spin, TreeSelect, message } from 'antd';
import pageStyles from '@/common/pageLayout.less';
import { MaterialManageAPI } from '../common/type';
import { UploadFormCommon } from '@/components/UploadForm';
import { useRequest } from 'umi';
import { adminAreadDataGet } from '@/services/BaseLayout';
import { arieaEchoRender, getLoadMapList, getSelectDataCommon, getTenantID, onCloseModalCommon } from '@/utils';
import { ILoadMapTypeAll } from '@/common';
import { addMaterialServices, detailMaterialServices, editMaterialServices } from '../services';
import ApplySignModal from './SignModal';
import { RegularExpression } from '@/common/constVariable';
import { formatDecimal } from '../../Acommon';
import moment from 'moment';

/**
 * 新增编辑modal
 * @param curRes  权限
 * @param onClose  取消modal
 * @param checkRows  点击的行数据
 * @param isShowModal  modal 是否显示
 * @param reloadManage  刷新管理页面
 */
const UpdataMaterialModal: React.FC<MaterialManageAPI.IUpdateModal> = ({ onClose, curRes, checkRows, isShowModal, reloadManage }) => {
  /**货物类-字典编码*/
  const HWL_Code = `${getTenantID()}${ILoadMapTypeAll.PURCHASE_CATEGORY}1000`;

  const loadMdicIds: string[] = [
    `${getTenantID()}${ILoadMapTypeAll.MATERIAL_BRAND}`,
    `${getTenantID()}${ILoadMapTypeAll.MATERIAL_MIDI}`,
    `${getTenantID()}${ILoadMapTypeAll.MATERIAL_TYPE}`,
    `${getTenantID()}${ILoadMapTypeAll.PURCHASE_CATEGORY}`,
  ];

  const { loadMapInfo: loadMdicMapList, mapLoading } = getLoadMapList(loadMdicIds);

  /**弹框的ref*/
  const updateModalRef: Ref<IOneModalRef> = useRef(null);

  /**updata表单的ref*/
  const [updateForm] = Form.useForm();

  /**spin的flag*/
  const [spinLoading, setspinLoading] = useState(false);

  /**保存一份详情数据*/
  const [record, setRecord] = useState<Record<string, any>>({});

  /**保存上级岗位搜索输入框的值*/
  const [treeSearch, setTreeSearch] = useState<string>('');

  /**发布，申请弹窗*/
  const [isShowApplyModal, setIsShowApplyModal] = useState<Record<string, any>>({
    isShow: false,
    recordObj: {},
    type: null,
    select: null,
  });

  /**添加方法Callback*/
  const addMaterialCallback = (res: any) => {
    if (res?.msgFlag) {
      message.success(res?.msg);
      onCloseModalCommon(updateModalRef);
      reloadManage();
    }
  };

  /**详情方法Callback*/
  const detailMaterialCallback = (res: any) => {
    if (res?.msgFlag) {
      let resObj = res?.obj;
      setRecord(resObj);
      updateForm?.setFieldsValue({
        ...resObj,
        contaNode: arieaEchoRender(resObj),
      });
    }
  };

  /**编辑方法Callback*/
  const editMaterialCallback = (res: any) => {
    if (res?.msgFlag) {
      message.success(res?.msg);
      onCloseModalCommon(updateModalRef);
      reloadManage();
    }
  };

  /**添加方法services*/
  const { addMaterialRun, addMaterialLoading } = addMaterialServices(addMaterialCallback);

  /**详情方法services*/
  const { detailMaterialRun, detailMaterialLoading } = detailMaterialServices(detailMaterialCallback);

  /**编辑方法services*/
  const { editMaterialRun, editMaterialLoading } = editMaterialServices(editMaterialCallback);

  /**点击确定方法*/
  const onUpdataMaterial = () => {
    updateForm?.validateFields().then((res) => {
      res = { ...res, unitPrice: formatDecimal(res?.unitPrice) };
      if (checkRows?.id) {
        editMaterialRun({ ...record, ...res });
      } else {
        if (curRes?.['/materialController/publish']) res.signType = 0;
        if (curRes?.['/materialController/applyMaterial']) res.signType = 1;
        addMaterialRun(res);
      }
    });
  };

  /**点击取消方法*/
  const onCanCelMaterial = () => {
    onCloseModalCommon(updateModalRef);
  };

  /**点击发布*/
  const onPublishMaterial = () => {
    updateForm?.validateFields().then((res) => {
      setIsShowApplyModal({
        isShow: true,
        recordObj: res,
        type: 'publish',
        select: 'name',
      });
    });
  };

  /**点击申请*/
  const onApplyMaterial = () => {
    updateForm?.validateFields().then((res) => {
      setIsShowApplyModal({
        isShow: true,
        recordObj: res,
        type: 'apply',
        select: 'name',
      });
    });
  };

  // /**获取行政区域*/
  // const areadList = useRequest(() => {
  //   return adminAreadDataGet({});
  // });

  /**公用loading*/
  const allLoading = useMemo(() => {
    if (spinLoading || addMaterialLoading || detailMaterialLoading || editMaterialLoading) {
      return true;
    } else {
      return false;
    }
  }, [spinLoading, addMaterialLoading, detailMaterialLoading, editMaterialLoading]);

  /** 物料类型编码 */
  const [materialType, setMaterialType] = useState<string>(record.materialType ? record.materialType : '');

  /** 规格要求(参数)编码 */
  const [materialNum, setMaterialNum] = useState<string>(record.materialNum ? record.materialNum : '');

  /** 物料类型选中*/
  const selectMaterialType = (value: string, record: any) => {
    if (checkRows?.id) {
      updateForm?.setFieldsValue({
        materialNum: record?.shortCode,
      });
    } else {
      setMaterialType(record?.shortCode);
    }
  };

  /** 规格要求（参数）改变完成  改变后  */
  const handleChangeSpecInfo = (e: any) => {
    // if (checkRows?.id) {
    //   updateForm?.setFieldsValue({
    //     materialNum: updateForm?.getFieldsValue().materialType + e?.target?.value?.slice(0, 6),
    //   });
    // } else {
    //   setMaterialNum(e?.target?.value);
    // }
  };
  /** 物料编码 */
  useEffect(() => {
    updateForm?.setFieldsValue({
      materialNum: materialType ? materialType + materialNum.slice(0, 6) + moment().format('YYYY').slice(2) : null,
    });
  }, [materialType, materialNum]);
  useEffect(() => {
    /**触发详情接口*/
    if (checkRows?.id) {
      detailMaterialRun({ id: checkRows?.id });
    }
  }, [checkRows]);

  useEffect(() => {
    if (isShowModal === true) {
      setspinLoading(true);
      setTimeout(() => {
        setspinLoading(false);
      }, 800);
    }
  }, [isShowModal]);

  // 处理树数据
  const orgTreeData = (data: any[]): any[] => {
    return data?.map((item: any) => {
      const name = item?.name;
      const nameLength = name?.length;
      const select = name?.search(treeSearch);
      const searchLength = treeSearch?.length;
      const afterStr = name?.slice(0, select);
      const selectStr = treeSearch;
      const beforeStr = name?.slice(select + searchLength, nameLength);
      const titleTree =
        select > -1 && selectStr ? (
          <span className={pageStyles['over-flow-hidden']}>
            {afterStr}
            <span style={{ color: '#f50' }}>{selectStr}</span>
            {beforeStr}
          </span>
        ) : (
          <span className={pageStyles['over-flow-hidden']}>{item?.name}</span>
        );

      if (item?.children && item?.children?.length > 0) {
        return {
          ...item,
          title: (
            <div
              style={{
                display: 'flex',
                alignItems: 'center',
                paddingRight: 20,
              }}
              id={item?.id}
            >
              {titleTree}
            </div>
          ),
          searchTitle: item?.name,
          key: item?.id,
          value: item?.id,
          // disabled: !item?.pID,
          children: orgTreeData(item?.children),
        };
      }
      return {
        ...item,
        title: (
          <div
            style={{
              display: 'flex',
              alignItems: 'center',
              paddingRight: 20,
            }}
            id={item?.id}
          >
            {titleTree}
          </div>
        ),
        searchTitle: item?.name,
        key: item?.id,
        value: item?.id,
      };
    });
  };

  // 获取搜索框输入的值
  const treeSearchValue = useCallback(
    (valText: string) => {
      setTreeSearch(valText);
    },
    [treeSearch],
  );

  return (
    <>
      <OneModal
        open={true}
        getContainer={false}
        ref={updateModalRef}
        title={checkRows?.id ? '编辑物料' : '添加物料'}
        onCancel={onClose}
        onOk={onUpdataMaterial}
        width={document.body.clientWidth * 0.45}
        bodyStyle={{ padding: '5px 10px' }}
        footer={[
          <Button key="back" loading={allLoading} onClick={onCanCelMaterial}>
            关闭
          </Button>,
          curRes?.['/materialController/publish'] && !checkRows?.id && (
            <>
              <Button
                key="issue"
                type="primary"
                loading={allLoading}
                onClick={() => {
                  onPublishMaterial();
                }}
              >
                发布
              </Button>
            </>
          ),
          curRes?.['/materialController/publish'] ? (
            <></>
          ) : (
            curRes?.['/materialController/applyMaterial'] &&
            !checkRows?.id && (
              <>
                <Button
                  key="apply"
                  type="primary"
                  loading={allLoading}
                  onClick={() => {
                    onApplyMaterial();
                  }}
                >
                  申请
                </Button>
              </>
            )
          ),
          <Button key="submit" type="primary" loading={allLoading} onClick={onUpdataMaterial}>
            暂存
          </Button>,
        ]}
      >
        <Spin spinning={allLoading}>
          <div className={pageStyles['fromView-styles']}>
            <Form form={updateForm}>
              <Row>
                <Col span={12}>
                  <Form.Item
                    label="物料类型"
                    name="materialType"
                    rules={[
                      {
                        required: true,
                        message: '请选择物料类型',
                      },
                    ]}
                  >
                    <TreeSelect
                      placeholder="请选择"
                      showSearch={true}
                      loading={mapLoading}
                      treeNodeFilterProp={'searchTitle'}
                      treeData={orgTreeData(loadMdicMapList?.[`${getTenantID()}${ILoadMapTypeAll.MATERIAL_TYPE}`])}
                      onSearch={treeSearchValue}
                      onSelect={selectMaterialType}
                    />
                  </Form.Item>
                </Col>
                <Col span={12}>
                  <Form.Item
                    label="物料编码"
                    name="materialNum"
                    rules={[
                      // {
                      //   required: true,
                      //   message: '请输入物料编码',
                      // },
                      {
                        pattern: RegularExpression.numberOrLetter,
                        message: '编码格式不正确！',
                      },
                    ]}
                  >
                    <Input placeholder="自动生成" disabled />
                  </Form.Item>
                </Col>
                <Col span={12}>
                  <Form.Item
                    label="物料名称"
                    name="fullName"
                    rules={[
                      {
                        required: true,
                        message: '请输入物料名称',
                      },
                    ]}
                  >
                    <Input placeholder="请输入" />
                  </Form.Item>
                </Col>
                <Col span={12}>
                  <Form.Item label="供货分类" name="supplyType" initialValue={HWL_Code}>
                    <Select placeholder="请选择" loading={mapLoading} disabled>
                      {loadMdicMapList?.[`${getTenantID()}${ILoadMapTypeAll.PURCHASE_CATEGORY}`]?.map((item: any) => {
                        if (item?.id === HWL_Code) {
                          return (
                            <Select.Option key={item?.id} value={item?.id}>
                              {item?.name}
                            </Select.Option>
                          );
                        }
                      })}
                    </Select>
                  </Form.Item>
                </Col>
              </Row>
              <Row>
                {/* 【20230816-不在物料展示供货分类】 */}
                <Col span={24}>
                  <Form.Item
                    label="规格要求(参数)"
                    name="specInfo"
                    rules={[
                      {
                        required: true,
                        message: '请输入规格要求（参数）',
                      },
                      // {
                      //   pattern: RegularExpression?.noChinese,
                      //   message: '规格要求（参数）只能填字母和数字！',
                      // },
                    ]}
                  >
                    <Input.TextArea placeholder="请输入" allowClear maxLength={500} autoSize={{ minRows: 3 }} showCount onChange={handleChangeSpecInfo} />
                    {/* <Input placeholder="请输入规格要求（参数）" /> */}
                  </Form.Item>
                </Col>
              </Row>
              <Row>
                <Col span={24}>
                  <Form.Item
                    label="规格型号"
                    name="modelNum"
                    rules={[
                      {
                        required: false,
                        message: '请输入规格型号',
                      },
                    ]}
                  >
                    <Input placeholder="请输入" />
                  </Form.Item>
                </Col>
              </Row>
              <Row>
                <Col span={12}>
                  <Form.Item
                    label="参考单价"
                    name="unitPrice"
                    rules={[
                      {
                        required: false,
                        message: '请输入参考单价',
                      },
                      {
                        pattern: RegularExpression?.floatNumber,
                        message: '参考单价只能填数字！',
                      },
                      {
                        pattern: /^\d+(\.\d{1,2})?$/,
                        message: '最多可保留两位小数！',
                      },
                    ]}
                  >
                    <Input placeholder="请输入" addonAfter={'元'} />
                  </Form.Item>
                </Col>
                <Col span={12}>
                  <Form.Item
                    label="量化单位"
                    name="unitBusiness"
                    rules={[
                      {
                        required: true,
                        message: '请选择量化单位',
                      },
                    ]}
                  >
                    <Select placeholder="请选择" loading={mapLoading}>
                      {loadMdicMapList?.[`${getTenantID()}${ILoadMapTypeAll.MATERIAL_MIDI}`]?.map((item: any) => {
                        return (
                          <Select.Option key={item?.id} value={item?.id}>
                            {item?.name}
                          </Select.Option>
                        );
                      })}
                    </Select>
                  </Form.Item>
                </Col>
              </Row>
              <Row>
                <Col span={24}>
                  <Form.Item label="物料简介" name="paramsInfo">
                    <Input.TextArea placeholder="请输入" allowClear maxLength={200} autoSize={{ minRows: 3 }} showCount />
                  </Form.Item>
                </Col>
              </Row>
              <Row>
                <Col span={24}>
                  <UploadFormCommon
                    form={updateForm}
                    fileFormName={'imageInfo'}
                    fileFormDelName={'delLicenceUrl'}
                    name={'attachFile'}
                    spanCol={24}
                    inRowProportion={12}
                    label="相关图片"
                    required={false}
                    accept={'.jpg|.png|.jpeg'}
                    url={`/materialController/uploadFile`}
                    downloadUrl={`/materialController/downloadFile`}
                    delFunc={() => {}}
                    maxFile={5}
                    defaultFiles={record && record?.id ? record?.imageInfo : null}
                    fieldBusiPath={'purchase/material'}
                  >
                    上传
                  </UploadFormCommon>
                </Col>
              </Row>
              <Row>
                <Col></Col>
              </Row>
            </Form>
          </div>
        </Spin>

        {/* 发布申请弹窗 */}
        {isShowApplyModal?.isShow && (
          <ApplySignModal
            curRes={curRes}
            onClose={(res: any = false) => {
              setIsShowApplyModal({
                isShow: false,
                recordObj: {},
                type: null,
                select: null,
              });
              if (!res) {
                onCloseModalCommon(updateModalRef);
              }
            }}
            checkRows={isShowApplyModal?.recordObj}
            isShowModal={isShowApplyModal?.isShow}
            reloadManage={reloadManage}
            modalType={isShowApplyModal?.type}
            isShowIdName={isShowApplyModal?.select}
            onCloseModalParent={() => {
              onCloseModalCommon(updateModalRef);
            }}
          />
        )}
      </OneModal>
    </>
  );
};

export default UpdataMaterialModal;
